#import "VoiceRecordViewController.h"

@implementation VoiceRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.97 alpha:1.0];
    self.title = @"语音记录";
    
    // 添加导航栏按钮 - 使用 back 图片
    UIImage *backImage = [UIImage imageNamed:@"back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    // 添加点击手势来隐藏键盘
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    tapGesture.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGesture];
    
    [self setupAudioSession];
    [self setupUI];
    [self setupConstraints];
}

- (void)setupAudioSession {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *error;
    
    // 设置音频会话类别为录音和播放
    [session setCategory:AVAudioSessionCategoryPlayAndRecord 
                 withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker 
                       error:&error];
    
    if (error) {
        NSLog(@"设置音频会话类别失败: %@", error.localizedDescription);
    }
    
    // 激活音频会话
    [session setActive:YES error:&error];
    if (error) {
        NSLog(@"激活音频会话失败: %@", error.localizedDescription);
    }
}

- (void)setupUI {
    // 滚动视图
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    // 内容视图
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];
    
    // 录音区域
    UIView *recordSection = [self createSectionWithTitle:@"语音录制"];
    [self.contentView addSubview:recordSection];
    
    // 录音视图
    self.recordingView = [[UIView alloc] init];
    self.recordingView.translatesAutoresizingMaskIntoConstraints = NO;
    self.recordingView.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:1.0 alpha:1.0];
    self.recordingView.layer.cornerRadius = 12;
    self.recordingView.layer.borderWidth = 2;
    self.recordingView.layer.borderColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.95 alpha:1.0].CGColor;
    [recordSection addSubview:self.recordingView];
    
    // 录音按钮
    self.recordButton = [[UIButton alloc] init];
    self.recordButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.recordButton setTitle:@"🎤" forState:UIControlStateNormal];
    self.recordButton.titleLabel.font = [UIFont systemFontOfSize:40];
    self.recordButton.backgroundColor = [UIColor colorWithRed:1.0 green:0.3 blue:0.3 alpha:1.0];
    self.recordButton.layer.cornerRadius = 40;
    [self.recordButton addTarget:self action:@selector(toggleRecording) forControlEvents:UIControlEventTouchUpInside];
    [self.recordingView addSubview:self.recordButton];
    
    // 录音状态标签
    self.recordingStatusLabel = [[UILabel alloc] init];
    self.recordingStatusLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.recordingStatusLabel.text = @"点击开始录音";
    self.recordingStatusLabel.textAlignment = NSTextAlignmentCenter;
    self.recordingStatusLabel.font = [UIFont boldSystemFontOfSize:18];
    self.recordingStatusLabel.textColor = [UIColor darkGrayColor];
    [self.recordingView addSubview:self.recordingStatusLabel];
    
    // 时间标签
    self.timeLabel = [[UILabel alloc] init];
    self.timeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.timeLabel.text = @"00:00";
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.font = [UIFont monospacedDigitSystemFontOfSize:24 weight:UIFontWeightMedium];
    self.timeLabel.textColor = [UIColor colorWithRed:1.0 green:0.3 blue:0.3 alpha:1.0];
    [self.recordingView addSubview:self.timeLabel];
    
    // 波形视图
    self.waveformView = [[UIView alloc] init];
    self.waveformView.translatesAutoresizingMaskIntoConstraints = NO;
    self.waveformView.backgroundColor = [UIColor clearColor];
    [self.recordingView addSubview:self.waveformView];
    
    // 播放按钮
    self.playButton = [[UIButton alloc] init];
    self.playButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.playButton setTitle:@"▶️ 播放录音" forState:UIControlStateNormal];
    [self.playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.playButton.backgroundColor = [UIColor colorWithRed:0.2 green:0.6 blue:1.0 alpha:1.0];
    self.playButton.layer.cornerRadius = 25;
    self.playButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    self.playButton.hidden = YES;
    [self.playButton addTarget:self action:@selector(playRecording) forControlEvents:UIControlEventTouchUpInside];
    [recordSection addSubview:self.playButton];
    
    // 物品信息区域
    UIView *infoSection = [self createSectionWithTitle:@"物品信息"];
    [self.contentView addSubview:infoSection];
    
    // 物品名称
    self.nameField = [[UITextField alloc] init];
    self.nameField.translatesAutoresizingMaskIntoConstraints = NO;
    self.nameField.placeholder = @"请输入物品名称";
    self.nameField.borderStyle = UITextBorderStyleRoundedRect;
    self.nameField.backgroundColor = [UIColor whiteColor];
    self.nameField.layer.cornerRadius = 8;
    self.nameField.font = [UIFont systemFontOfSize:16];
    self.nameField.delegate = self;
    self.nameField.returnKeyType = UIReturnKeyNext;
    [infoSection addSubview:self.nameField];
    
    // 物品描述
    self.descTextView = [[UITextView alloc] init];
    self.descTextView.translatesAutoresizingMaskIntoConstraints = NO;
    self.descTextView.backgroundColor = [UIColor whiteColor];
    self.descTextView.layer.cornerRadius = 8;
    self.descTextView.layer.borderWidth = 1;
    self.descTextView.layer.borderColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1.0].CGColor;
    self.descTextView.font = [UIFont systemFontOfSize:16];
    self.descTextView.delegate = self;
    [infoSection addSubview:self.descTextView];
    
    // 占位符标签
    self.placeholderLabel = [[UILabel alloc] init];
    self.placeholderLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.placeholderLabel.text = @"请输入物品描述或存放位置";
    self.placeholderLabel.textColor = [UIColor lightGrayColor];
    self.placeholderLabel.font = [UIFont systemFontOfSize:16];
    [self.descTextView addSubview:self.placeholderLabel];
    
    // 分类选择
    self.categorySegment = [[UISegmentedControl alloc] initWithItems:@[@"日用品", @"电子产品", @"文件证件", @"其他"]];
    self.categorySegment.translatesAutoresizingMaskIntoConstraints = NO;
    self.categorySegment.selectedSegmentIndex = 0;
    self.categorySegment.backgroundColor = [UIColor whiteColor];
    self.categorySegment.selectedSegmentTintColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
    [infoSection addSubview:self.categorySegment];
    
    // 保存按钮 - 移到主视图，固定在底部
    self.saveButton = [[UIButton alloc] init];
    self.saveButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.saveButton setTitle:@"保存记录" forState:UIControlStateNormal];
    [self.saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.saveButton.backgroundColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
    self.saveButton.layer.cornerRadius = 25;
    self.saveButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.saveButton addTarget:self action:@selector(saveRecord) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.saveButton]; // 直接添加到主视图
}

- (UIView *)createSectionWithTitle:(NSString *)title {
    UIView *section = [[UIView alloc] init];
    section.translatesAutoresizingMaskIntoConstraints = NO;
    section.backgroundColor = [UIColor whiteColor];
    section.layer.cornerRadius = 12;
    section.layer.shadowColor = [UIColor blackColor].CGColor;
    section.layer.shadowOffset = CGSizeMake(0, 2);
    section.layer.shadowOpacity = 0.1;
    section.layer.shadowRadius = 4;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.text = title;
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textColor = [UIColor darkGrayColor];
    [section addSubview:titleLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [titleLabel.topAnchor constraintEqualToAnchor:section.topAnchor constant:16],
        [titleLabel.leadingAnchor constraintEqualToAnchor:section.leadingAnchor constant:16],
        [titleLabel.trailingAnchor constraintEqualToAnchor:section.trailingAnchor constant:-16]
    ]];
    
    return section;
}

- (void)setupConstraints {
    UIView *recordSection = [self.contentView.subviews firstObject];
    UIView *infoSection = [self.contentView.subviews lastObject];
    
    [NSLayoutConstraint activateConstraints:@[
        // 滚动视图 - 修改底部约束，为保存按钮留出空间
        [self.scrollView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.saveButton.topAnchor constant:-10],
        
        // 内容视图
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
        
        // 录音区域
        [recordSection.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:20],
        [recordSection.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
        [recordSection.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20],
        [recordSection.heightAnchor constraintEqualToConstant:320],
        
        // 录音视图
        [self.recordingView.topAnchor constraintEqualToAnchor:recordSection.topAnchor constant:60],
        [self.recordingView.leadingAnchor constraintEqualToAnchor:recordSection.leadingAnchor constant:20],
        [self.recordingView.trailingAnchor constraintEqualToAnchor:recordSection.trailingAnchor constant:-20],
        [self.recordingView.heightAnchor constraintEqualToConstant:180],
        
        // 录音按钮
        [self.recordButton.centerXAnchor constraintEqualToAnchor:self.recordingView.centerXAnchor],
        [self.recordButton.topAnchor constraintEqualToAnchor:self.recordingView.topAnchor constant:20],
        [self.recordButton.widthAnchor constraintEqualToConstant:80],
        [self.recordButton.heightAnchor constraintEqualToConstant:80],
        
        // 状态标签
        [self.recordingStatusLabel.topAnchor constraintEqualToAnchor:self.recordButton.bottomAnchor constant:10],
        [self.recordingStatusLabel.leadingAnchor constraintEqualToAnchor:self.recordingView.leadingAnchor constant:10],
        [self.recordingStatusLabel.trailingAnchor constraintEqualToAnchor:self.recordingView.trailingAnchor constant:-10],
        
        // 时间标签
        [self.timeLabel.topAnchor constraintEqualToAnchor:self.recordingStatusLabel.bottomAnchor constant:5],
        [self.timeLabel.leadingAnchor constraintEqualToAnchor:self.recordingView.leadingAnchor constant:10],
        [self.timeLabel.trailingAnchor constraintEqualToAnchor:self.recordingView.trailingAnchor constant:-10],
        
        // 波形视图
        [self.waveformView.topAnchor constraintEqualToAnchor:self.timeLabel.bottomAnchor constant:10],
        [self.waveformView.leadingAnchor constraintEqualToAnchor:self.recordingView.leadingAnchor constant:20],
        [self.waveformView.trailingAnchor constraintEqualToAnchor:self.recordingView.trailingAnchor constant:-20],
        [self.waveformView.bottomAnchor constraintEqualToAnchor:self.recordingView.bottomAnchor constant:-10],
        
        // 播放按钮
        [self.playButton.topAnchor constraintEqualToAnchor:self.recordingView.bottomAnchor constant:20],
        [self.playButton.centerXAnchor constraintEqualToAnchor:recordSection.centerXAnchor],
        [self.playButton.widthAnchor constraintEqualToConstant:140],
        [self.playButton.heightAnchor constraintEqualToConstant:50],
        
        // 信息区域
        [infoSection.topAnchor constraintEqualToAnchor:recordSection.bottomAnchor constant:20],
        [infoSection.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
        [infoSection.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20],
        [infoSection.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-20],
        [infoSection.heightAnchor constraintEqualToConstant:280],
        
        // 保存按钮 - 固定在页面底部
        [self.saveButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
        [self.saveButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],
        [self.saveButton.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-20],
        [self.saveButton.heightAnchor constraintEqualToConstant:50]
    ]];
    
    [self setupInfoSectionConstraints:infoSection];
}

- (void)setupInfoSectionConstraints:(UIView *)infoSection {
    [NSLayoutConstraint activateConstraints:@[
        // 物品名称 - 修复：减少顶部间距
        [self.nameField.topAnchor constraintEqualToAnchor:infoSection.topAnchor constant:40],
        [self.nameField.leadingAnchor constraintEqualToAnchor:infoSection.leadingAnchor constant:16],
        [self.nameField.trailingAnchor constraintEqualToAnchor:infoSection.trailingAnchor constant:-16],
        [self.nameField.heightAnchor constraintEqualToConstant:44],
        
        // 物品描述
        [self.descTextView.topAnchor constraintEqualToAnchor:self.nameField.bottomAnchor constant:16],
        [self.descTextView.leadingAnchor constraintEqualToAnchor:infoSection.leadingAnchor constant:16],
        [self.descTextView.trailingAnchor constraintEqualToAnchor:infoSection.trailingAnchor constant:-16],
        [self.descTextView.heightAnchor constraintEqualToConstant:80],
        
        // 占位符
        [self.placeholderLabel.topAnchor constraintEqualToAnchor:self.descTextView.topAnchor constant:8],
        [self.placeholderLabel.leadingAnchor constraintEqualToAnchor:self.descTextView.leadingAnchor constant:8],
        
        // 分类选择器
        [self.categorySegment.topAnchor constraintEqualToAnchor:self.descTextView.bottomAnchor constant:20],
        [self.categorySegment.leadingAnchor constraintEqualToAnchor:infoSection.leadingAnchor constant:16],
        [self.categorySegment.trailingAnchor constraintEqualToAnchor:infoSection.trailingAnchor constant:-16],
        [self.categorySegment.heightAnchor constraintEqualToConstant:32] // 添加固定高度
    ]];
}

#pragma mark - Actions

- (void)toggleRecording {
    if (self.isRecording) {
        [self stopRecording];
    } else {
        [self startRecording];
    }
}

- (void)startRecording {
    NSString *fileName = [NSString stringWithFormat:@"voice_%@.m4a", @([[NSDate date] timeIntervalSince1970])];
    self.audioFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    
    NSDictionary *settings = @{
        AVFormatIDKey: @(kAudioFormatMPEG4AAC),
        AVSampleRateKey: @44100,
        AVNumberOfChannelsKey: @2,
        AVEncoderAudioQualityKey: @(AVAudioQualityHigh)
    };
    
    NSError *error;
    self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:self.audioFilePath] settings:settings error:&error];
    
    if (error) {
        NSLog(@"录音初始化失败: %@", error.localizedDescription);
        return;
    }
    
    self.audioRecorder.delegate = self;
    self.audioRecorder.meteringEnabled = YES;
    
    if ([self.audioRecorder record]) {
        self.isRecording = YES;
        self.recordingTime = 0;
        
        // 更新UI
        [self.recordButton setTitle:@"⏹️" forState:UIControlStateNormal];
        self.recordButton.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
        self.recordingStatusLabel.text = @"录音中...";
        
        // 启动计时器
        self.recordingTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateRecordingTime) userInfo:nil repeats:YES];
    }
}

- (void)stopRecording {
    [self.audioRecorder stop];
    [self.recordingTimer invalidate];
    self.recordingTimer = nil;
    self.isRecording = NO;
    
    // 更新UI
    [self.recordButton setTitle:@"🎤" forState:UIControlStateNormal];
    self.recordButton.backgroundColor = [UIColor colorWithRed:1.0 green:0.3 blue:0.3 alpha:1.0];
    self.recordingStatusLabel.text = @"录音完成";
    self.playButton.hidden = NO;
}

- (void)updateRecordingTime {
    self.recordingTime += 0.1;
    int minutes = (int)self.recordingTime / 60;
    int seconds = (int)self.recordingTime % 60;
    self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    
    // 更新音量指示器
    [self.audioRecorder updateMeters];
    float power = [self.audioRecorder averagePowerForChannel:0];
    [self updateWaveformWithPower:power];
}

- (void)updateWaveformWithPower:(float)power {
    // 简单的波形可视化
    CGFloat normalizedPower = (power + 80) / 80.0; // 归一化到0-1
    normalizedPower = MAX(0, MIN(1, normalizedPower));
    
    // 清除之前的波形
    for (UIView *subview in self.waveformView.subviews) {
        [subview removeFromSuperview];
    }
    
    // 绘制新的波形条
    CGFloat barWidth = 4;
    CGFloat spacing = 2;
    NSInteger barCount = self.waveformView.bounds.size.width / (barWidth + spacing);
    
    for (NSInteger i = 0; i < barCount; i++) {
        UIView *bar = [[UIView alloc] init];
        bar.backgroundColor = [UIColor colorWithRed:1.0 green:0.3 blue:0.3 alpha:0.7];
        bar.layer.cornerRadius = barWidth / 2;
        
        CGFloat height = normalizedPower * self.waveformView.bounds.size.height * (0.5 + 0.5 * (arc4random() % 100) / 100.0);
        CGFloat x = i * (barWidth + spacing);
        CGFloat y = (self.waveformView.bounds.size.height - height) / 2;
        
        bar.frame = CGRectMake(x, y, barWidth, height);
        [self.waveformView addSubview:bar];
    }
}

- (void)playRecording {
    if (!self.audioFilePath) {
        NSLog(@"音频文件路径为空");
        return;
    }
    
    // 检查文件是否存在
    if (![[NSFileManager defaultManager] fileExistsAtPath:self.audioFilePath]) {
        NSLog(@"音频文件不存在: %@", self.audioFilePath);
        return;
    }
    
    // 重新设置音频会话为播放模式
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    if (sessionError) {
        NSLog(@"设置播放音频会话失败: %@", sessionError.localizedDescription);
    }
    
    NSError *error;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.audioFilePath] error:&error];
    
    if (error) {
        NSLog(@"播放失败: %@", error.localizedDescription);
        return;
    }
    
    self.audioPlayer.delegate = self;
    
    // 准备播放
    if (![self.audioPlayer prepareToPlay]) {
        NSLog(@"音频播放器准备失败");
        return;
    }
    
    // 开始播放
    if ([self.audioPlayer play]) {
        NSLog(@"开始播放音频文件: %@", self.audioFilePath);
        [self.playButton setTitle:@"🔊 播放中..." forState:UIControlStateNormal];
        self.playButton.enabled = NO;
    } else {
        NSLog(@"播放启动失败");
    }
}

- (void)saveRecord {
    if (!self.audioFilePath || self.nameField.text.length == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请录制语音并填写物品名称" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    NSArray *categories = @[@"日用品", @"电子产品", @"文件证件", @"其他"];
    NSString *category = categories[self.categorySegment.selectedSegmentIndex];
    
    NSDictionary *itemData = @{
        @"name": self.nameField.text,
        @"desc": self.descTextView.text ?: @"",
        @"category": category,
        @"time": [self getCurrentTimeString],
        @"audioPath": self.audioFilePath
    };
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didFinishVoiceRecordWithData:)]) {
        [self.delegate didFinishVoiceRecordWithData:itemData];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)cancelAction {
    if (self.isRecording) {
        [self stopRecording];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)getCurrentTimeString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM-dd HH:mm";
    return [formatter stringFromDate:[NSDate date]];
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    self.placeholderLabel.hidden = textView.text.length > 0;
}

#pragma mark - Keyboard Management

- (void)dismissKeyboard {
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 移除键盘通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardFrame.size.height;
    NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
        self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset;
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSTimeInterval animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.scrollView.contentInset = UIEdgeInsetsZero;
        self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.nameField) {
        [self.descTextView becomeFirstResponder];
    }
    return YES;
}

#pragma mark - AVAudioRecorderDelegate

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    if (flag) {
        NSLog(@"录音完成成功，文件路径: %@", self.audioFilePath);
        
        // 检查录音文件是否存在和大小
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:self.audioFilePath]) {
            NSDictionary *attributes = [fileManager attributesOfItemAtPath:self.audioFilePath error:nil];
            NSNumber *fileSize = [attributes objectForKey:NSFileSize];
            NSLog(@"录音文件大小: %@ bytes", fileSize);
            
            if ([fileSize longLongValue] > 0) {
                self.playButton.hidden = NO;
            } else {
                NSLog(@"录音文件为空");
            }
        } else {
            NSLog(@"录音文件不存在");
        }
    } else {
        NSLog(@"录音失败");
    }
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
    NSLog(@"录音编码错误: %@", error.localizedDescription);
}

#pragma mark - AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"播放完成，成功: %@", flag ? @"是" : @"否");
    
    // 恢复录音和播放模式
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord
             withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
                   error:nil];
    
    [self.playButton setTitle:@"▶️ 播放录音" forState:UIControlStateNormal];
    self.playButton.enabled = YES;
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    NSLog(@"播放解码错误: %@", error.localizedDescription);
    [self.playButton setTitle:@"▶️ 播放录音" forState:UIControlStateNormal];
    self.playButton.enabled = YES;
}

@end

